﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;

namespace DailyNote.AppCode
{
    public class AutoStart
    {
        private static readonly string SelfStartupRegistryName = "DailyNote";
        public static void SetSelfStartup()
        {
            if (System.Windows.Forms.MessageBox.Show("是否打开程序的自动启动功能？", "提示",
               System.Windows.Forms.MessageBoxButtons.YesNo, System.Windows.Forms.MessageBoxIcon.Question) ==
                System.Windows.Forms.DialogResult.Yes)
            {
                SetSelfStartup_On();
            }
            else
            {
                SetSelfStartup_Off();
            }
        }
        private static void SetSelfStartup_Off()
        {
            try
            {
                Registry.LocalMachine.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run")
                    .DeleteValue(SelfStartupRegistryName);
            }
            catch
            {
            }
        }
        private static void SetSelfStartup_On()
        {
            string fileName = Process.GetCurrentProcess().MainModule.FileName;
            try
            {
                Registry.LocalMachine.CreateSubKey(@"Software\Microsoft\Windows\CurrentVersion\Run")
                    .SetValue(SelfStartupRegistryName, fileName);
            }
            catch
            {
                System.Windows.Forms.MessageBox.Show("设置开机自启动失败，可能是没有足够的权限！");
            }
        }
    }
}
